package com.xyj.week01;

/**
 * 寻找链表的中点
 */
public class T4 {


    public static void main(String[] args) {
        //初始化环形链表
        Node node = new Node(0);
        Node node1 = new Node(1);
        Node node2 = new Node(2);
        Node node3 = new Node(3);
        Node node4 = new Node(4);
        node.next=node1;
        node1.next=node2;
        node2.next=node3;
        node3.next=node4;
        System.out.println("链表的中点为"+getTheMidNode(node));
    }

    /**
     * 快慢指针  当快指针到达终点时，慢指针到达中点
     * @param head 头节点
     * @return 中点
     */
    public static Node getTheMidNode(Node head){
        Node fast=head;
        Node slow=head;
        while (fast.next!=null&&fast.next.next!=null){
            fast=fast.next.next;
            slow=slow.next;
        }
        return slow;
    }
}
